<?php
// +----------------------------------------------------------------------
// | TYCMS [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: aliang <461321026@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\Db;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\Category as CategoryModel;
use app\admin\model\Options as OptionsModel;
use app\admin\model\GoodsOrder as GoodsOrderModel;
class Goods extends Base
{
    var $mode = 'goods';
    var $state_pay_list = [
        '-1'=>'取消支付',
        '1' =>'待付款',
        '2' =>'已付款',
    ];
    var $state_trade_list = [
        '-1' => '交易取消',
        '1'  => '待确认',
        '2'  => '已确认未发货',
        '3'  => '已发货',
        '4'  => '确认收货',
        '5'  => '已评论',
        '9'  => '交易结束',
    ];
    
    /**
     * 商品列表
     */
	public function goods_list()
	{
		$keytype = input('keytype','goods_title');
		$key     = input('key');
		$news_l  = input('news_l');
		$status  = input('status','');
		$cate    = input('cate',0);
		$diyflag=input('diyflag','');
		//查询：时间格式过滤 获取格式 2015-11-12 - 2015-11-18
		$sldate=input('reservation','');
		$arr = explode(" - ",$sldate);
        if(count($arr)==2){
            $arrdateone=strtotime($arr[0]);
            $arrdatetwo=strtotime($arr[1].' 23:55:55');
            $map['add_times'] = array(array('egt',$arrdateone),array('elt',$arrdatetwo),'AND');
        }
		//map架构查询条件数组
		$map['goods_back']= 0;
		if(!empty($key)){
			if($keytype=='goods_title'){
				$map[$keytype]= array('like',"%".$key."%");
			}else{
				$map[$keytype]= $key;
			}
		}
		if ($status!='')
			$map['status']= array('eq',$status);

		if (!empty($news_l))
			$map['goods_l']= array('eq',$news_l);

		if ($cate!=''){
			$ids = get_cate_byid('category',$cate,1,2);
			$map['cid']= array('in',implode(",", $ids));
		}
		
		$where = $diyflag ? " FIND_IN_SET('$diyflag',goods_flag) ":'';
		$good_model =new GoodsModel;
		$goods_list =$good_model->alias("a")->field('a.*,b.cid,c.cate_name')
				->join(config('database.prefix').'goods_cate b','a.id = b.gid')
				->join(config('database.prefix').'category c','b.cid =c.id')
				->where($map)->where($where)->order('id desc')->paginate(config('paginate.list_rows'),false,['query'=>get_query()]);
		
		 
		
		$show = $goods_list->render();
		$show = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$show);
		$this->assign('page',$show);
		//商品属性数据
		$diyflag_list=Db::name('diyflag')->where('diyflag_model',$this->mode)->select();
		$this->assign('diyflag',$diyflag_list);
		//栏目数据
		
		
		$where=array();
		$where['model'] = array('eq',$this->mode);
		$where['cate_open']= array('eq',1);
		$cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
		$menu_text = menu_left($cate_list_all,'id','parentid');
		$this->assign('menu',$menu_text);
		
		
		$this->assign('status',$status);
		$this->assign('cate',$cate);
		$this->assign('keytype',$keytype);
		$this->assign('keyy',$key);
		$this->assign('news_l',$news_l);
		$this->assign('sldate',$sldate);
		$this->assign('diyflag_check',$diyflag);

		$this->assign('goods',$goods_list);
		if(request()->isAjax()){
			return $this->fetch('ajax_goods_list');
		}else{
			return $this->fetch();
		}		
	}
    /**
     * 添加显示
     */
	public function goods_list_add()
	{
	    
	    //商品属性数据
	    $diyflag_list=Db::name('diyflag')->where('diyflag_model',$this->mode)->select();
	    $this->assign('diyflag',$diyflag_list);
	    //栏目数据
	    
	    
	    $where=array();
	    $where['model'] = array('eq',$this->mode);
	    $where['cate_open']= array('eq',1);
	    $cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
	    $menu_text = menu_left($cate_list_all,'id','parentid');
	    $this->assign('menu',$menu_text);

		$cid = input('cid',0,'intval');
	     
		$source=Db::name('source')->select();
		$this->assign('cid',$cid);
                 
        $member_list = Db::name("member_group")->where("member_group_open","1")->field('member_group_name as name,member_group_id as id')->select();
        $this->assign('member_list',$member_list);
        $this->assign('site_bilv',config('options.site_bilv'));
		return $this->fetch();
	}
    /**
     * 添加操作
     */
	public function goods_list_runadd()
	{
		if (!request()->isAjax()){
			$this->error('提交方式不正确',url('admin/Goods/goods_list'));
		}
		//上传图片部分
		$img_one='';
		$picall_url='';
		$file  = request()->file('pic_one');
		$files = request()->file('pic_all');
		if($file || $files) {
			if(config('storage.storage_open')){
				//七牛
				$upload = \Qiniu::instance();
				$info = $upload->upload();
				$error = $upload->getError();
				if ($info) {
					if($file && $files){
						//有单图、多图
						if(!empty($info['pic_one'])) $img_one= config('storage.domain').$info['pic_one'][0]['key'];
						if(!empty($info['pic_all'])) {
							foreach ($info['pic_all'] as $file) {
								$img_url=config('storage.domain').$file['key'];
								$picall_url = $img_url . ',' . $picall_url;
							}
						}
					}elseif($file){
						//单图
						$img_one= config('storage.domain').$info[0]['key'];
					}else{
						//多图
						foreach ($info as $file) {
							$img_url=config('storage.domain').$file['key'];
							$picall_url = $img_url . ',' . $picall_url;
						}
					}
				}else{
					$this->error($error,url('admin/Goods/goods_list'));//否则就是上传错误，显示错误原因
				}
			}else{
				$validate = config('upload_validate');
				//单图
				if ($file) {
					$info = $file[0]->validate($validate)->rule('uniqid')->move(ROOT_PATH . config('upload_path') . DS . date('Y-m-d'));
					if ($info) {
						$img_url = config('upload_path'). '/' . date('Y-m-d') . '/' . $info->getFilename();
						//写入数据库
						$data['uptime'] = time();
						$data['filesize'] = $info->getSize();
						$data['path'] = $img_url;
						Db::name('plug_files')->insert($data);
						$img_one = $img_url;
					} else {
						$this->error($file->getError(), url('admin/Goods/goods_list'));//否则就是上传错误，显示错误原因
					}
				}
				//多图
				if ($files) {
					foreach ($files as $file) {
						$info = $file->validate($validate)->rule('uniqid')->move(ROOT_PATH . config('upload_path') . DS . date('Y-m-d'));
						if ($info) {
							$img_url = config('upload_path'). '/' . date('Y-m-d') . '/' . $info->getFilename();
							//写入数据库
							$data['uptime'] = time();
							$data['filesize'] = $info->getSize();
							$data['path'] = $img_url;
							Db::name('plug_files')->insert($data);
							$picall_url = $img_url . ',' . $picall_url;
						} else {
							$this->error($file->getError(), url('admin/Goods/goods_list'));//否则就是上传错误，显示错误原因
						}
					}
				}
			}
		}
		//获取商品属性
		$goods_flag=input('post.goods_flag/a');
		$flag=array();
		if(!empty($goods_flag)){
			foreach ($goods_flag as $v){
				$flag[]=$v;
			}
		}
		$flagdata=implode(',',$flag);
		$sl_data=array(
			'goods_title'=>input('goods_title'),
			'goods_flag' =>$flagdata,
			'price_cb'   =>input('price_cb'),
			'price'      =>input('price',''),
			'percent'    =>input('percent',''),
			'count_goods'=>input('count_goods',0),
		    'count_already'=>input('count_already',0),
			'goods_pic_type'=>input('goods_pic_type'),
			'goods_pic_content'=>input('goods_pic_content',''),
			'goods_pic_allurl'=>$picall_url,//多图路径
			'thumb'=>$img_one,//封面图片路径
			'status'=>input('status',0),
			'content'=>htmlspecialchars_decode(input('content')),
			'add_times'=>time(),
			'listorder'=>input('listorder',50,'intval'),
		);
		
		$gid = Db::name("goods")->insertGetid($sl_data);
		if($gid !==false){
		   $cid = input('cid');
		   $cid = is_array($cid) ? $cid :[$cid];
		   foreach($cid as $vv){
		     if(intval($vv) > 0)  
		       Db::name("goods_cate")->insert(['gid'=>$gid,'cid'=>$vv]);  
		   }
		   $prices = input('post.prices/a');
		   $inArr  = [];
		   foreach($prices as $id=>$fee){
		      $inArr['price_'.$id] = $fee; 
		   }
		   $inArr['gid'] = $gid;
		   Db::name("goods_price")->insert($inArr);  
		   $continue=input('continue',0,'intval');
		   if($continue){
		       $this->success('商品添加成功,继续发布',url('admin/Goods/goods_list_add',['cid'=>input('cid')]));
		   }else{
		       $this->success('商品添加成功,返回列表页',url('admin/Goods/goods_list'));
		   }    
		}else{
		   $this->error('商品添加失败！');
		}

	}
    /**
     * 编辑显示
     */
	public function goods_list_edit()
	{
		$id = input('id');
		if (empty($id)){
			$this->error('参数错误',url('admin/Goods/goods_list'));
		}
		$goods_info = GoodsModel::get($id);
		  
		//多图字符串转换成数组
		$text     = $goods_info['news_pic_allurl'];
		$pic_list = array_filter(explode(",", $text));
		$this->assign('pic_list',$pic_list);
		
		//商品属性数据
		$diyflag_list=Db::name('diyflag')->where('diyflag_model',$this->mode)->select();
		$this->assign('diyflag',$diyflag_list);
		//栏目数据
		 
		 
		$where=array();
		$where['model'] = array('eq',$this->mode);
		$where['cate_open']= array('eq',1);
		$cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
		$menu_text = menu_left($cate_list_all,'id','parentid');
		$this->assign('menu',$menu_text);
		
		$fee = Db::name('goods_price')->where('gid',$id)->find();
		$member_list = Db::name("member_group")->where("member_group_open","1")->field('member_group_name as name,member_group_id as id')->select();
		foreach($member_list as $k=>$v){
		    $member_list[$k]['fee'] = isset($fee['price_'.$v['id']]) ? $fee['price_'.$v['id']] : $goods_info['price'];
		}
		
		$this->assign('member_list',$member_list);
		$this->assign('site_bilv',config('options.site_bilv'));
		
		$goods_info['cid']   = Db::name('goods_cate')->where('gid',$id)->value('cid');
 
		$this->assign('info',$goods_info);
		return $this->fetch();
	}
    /**
     * 编辑操作
     */
	public function goods_list_runedit()
	{
		if (!request()->isAjax()){
			$this->error('提交方式不正确',url('admin/Goods/goods_list'));
		}
		//获取图片上传后路径
		$pic_oldlist=input('pic_oldlist');//老多图字符串
		$img_one='';
		$picall_url='';
		$file = request()->file('pic_one');
		$files = request()->file('pic_all');
		//上传处理
		if($file || $files) {
			if(config('storage.storage_open')){
				//七牛
				$upload = \Qiniu::instance();
				$info = $upload->upload();
				$error = $upload->getError();
				if ($info) {
					if($file && $files){
						//有单图、多图
						if(!empty($info['pic_one'])) $img_one= config('storage.domain').$info['pic_one'][0]['key'];
						if(!empty($info['pic_all'])) {
							foreach ($info['pic_all'] as $file) {
								$img_url=config('storage.domain').$file['key'];
								$picall_url = $img_url . ',' . $picall_url;
							}
						}
					}elseif($file){
						//单图
						$img_one= config('storage.domain').$info[0]['key'];
					}else{
						//多图
						foreach ($info as $file) {
							$img_url=config('storage.domain').$file['key'];
							$picall_url = $img_url . ',' . $picall_url;
						}
					}
				}else{
					$this->error($error,url('admin/Goods/goods_list'));//否则就是上传错误，显示错误原因
				}
			}else{
				$validate = config('upload_validate');
				//单图
				if (!empty($file)) {
					$info = $file[0]->validate($validate)->rule('uniqid')->move(ROOT_PATH . config('upload_path') . DS . date('Y-m-d'));
					if ($info) {
						$img_url = config('upload_path'). '/' . date('Y-m-d') . '/' . $info->getFilename();
						//写入数据库
						$data['uptime'] = time();
						$data['filesize'] = $info->getSize();
						$data['path'] = $img_url;
						Db::name('plug_files')->insert($data);
						$img_one = $img_url;
					} else {
						$this->error($file->getError(), url('admin/Goods/goods_list'));//否则就是上传错误，显示错误原因
					}
				}
				//多图
				if (!empty($files)) {
					foreach ($files as $file) {
						$info = $file->validate($validate)->rule('uniqid')->move(ROOT_PATH . config('upload_path') . DS . date('Y-m-d'));
						if ($info) {
							$img_url = config('upload_path'). '/' . date('Y-m-d') . '/' . $info->getFilename();
							//写入数据库
							$data['uptime'] = time();
							$data['filesize'] = $info->getSize();
							$data['path'] = $img_url;
							Db::name('plug_files')->insert($data);
							$picall_url = $img_url . ',' . $picall_url;
						} else {
							$this->error($file->getError(), url('admin/Goods/goods_list'));//否则就是上传错误，显示错误原因
						}
					}
				}
			}
		}
		//获取商品属性
		$goods_flag=input('post.goods_flag/a');
		$flag=array();
		if(!empty($goods_flag)){
			foreach ($goods_flag as $v){
				$flag[]=$v;
			}
		}
		$flagdata=implode(',',$flag);
		$sl_data=array(
		    'id'         =>input('id'),
			'goods_title'=>input('goods_title'),
			'goods_flag' =>$flagdata,
			'price_cb'   =>input('price_cb'),
			'price'      =>input('price',''),
			'percent'    =>input('percent',''),
			'count_goods'=>input('count_goods',0),
		    'count_already'=>input('count_already',0),
			'goods_pic_type'=>input('goods_pic_type'),
			'goods_pic_content'=>input('goods_pic_content',''),
			'goods_pic_allurl'=>$picall_url,//多图路径
			'thumb'=>$img_one,//封面图片路径
			'status'=>input('status',0),
			'content'=>htmlspecialchars_decode(input('content')),
			'add_times'=>time(),
			'listorder'=>input('listorder',50,'intval'),
		);
		//图片字段处理
		if(!empty($img_one)){
			$sl_data['thumb'] = $img_one;
		}
		if(empty($sl_data['thumb']))
		   unset($sl_data['thumb']);
		$sl_data['goods_pic_allurl']=$pic_oldlist.$picall_url;
        $rst=GoodsModel::update($sl_data);
		if($rst!==false){
		    $cid = input('cid');
		    $gid = input('id/d');
		    $cid = is_array($cid) ? $cid :[$cid];
		    Db::name("goods_cate")->where('gid',$gid)->delete();
		    foreach($cid as $vv){
		        if(intval($vv) > 0)
		            Db::name("goods_cate")->insert(['gid'=>$gid,'cid'=>$vv]);
		    }
		    $prices = input('post.prices/a');
		    $inArr  = [];
		    foreach($prices as $id=>$fee){
		        $inArr['price_'.$id] = $fee;
		    }
		    Db::name("goods_price")->where('gid',$gid)->delete();
		    $inArr['gid'] = $gid;
		    Db::name("goods_price")->insert($inArr);
			$this->success('商品修改成功,返回列表页',url('admin/Goods/goods_list'));
		}else{
			$this->error('商品修改失败',url('admin/Goods/goods_list'));
		}
	}
    /**
     * 商品排序
     */
	public function goods_list_order()
	{
		if (!request()->isAjax()){
			$this->error('提交方式不正确',url('admin/Goods/goods_list'));
		}else{
			$list=[];
			foreach (input('post.') as $n_id => $news_order){
				$list[]=['id'=>$n_id,'listorder'=>$news_order];
			}
			$news_model=new GoodsModel;
			$news_model->saveAll($list);
			$this->success('排序更新成功',url('admin/Goods/goods_list'));
		}
	}
    /**
     * 删除至回收站(单个)
     */
	public function goods_list_del()
	{
		$p=input('p');
		$news_model=new GoodsModel;
		$rst=$news_model->where(array('id'=>input('id')))->setField('goods_back',1);//转入回收站
		if($rst!==false){
			$this->success('商品已转入回收站',url('admin/Goods/goods_list',array('p' => $p)));
		}else{
			$this -> error("删除商品失败！",url('admin/Goods/goods_list',array('p'=>$p)));
		}
	}
    /**
     * 删除至回收站(全选)
     */
	public function goods_list_alldel()
	{
		$p = input('p');
		$ids = input('n_id/a');
		if(empty($ids)){
			$this -> error("请选择删除商品",url('admin/Goods/goods_list',array('p'=>$p)));//判断是否选择了商品ID
		}
		if(is_array($ids)){//判断获取商品ID的形式是否数组
			$where = 'id in('.implode(',',$ids).')';
		}else{
			$where = 'id='.$ids;
		}
		$news_model=new GoodsModel;
		$rst=$news_model->where($where)->setField('goods_back',1);//转入回收站
		if($rst!==false){
			$this->success("成功把商品移至回收站！",url('admin/Goods/goods_list',array('p'=>$p)));
		}else{
			$this -> error("删除商品失败！",url('admin/Goods/goods_list',array('p'=>$p)));
		}
	}
    /**
     * 商品审核/取消审核
     */
	public function goods_list_state()
	{
		$id=input('x');
		$news_model=new GoodsModel;
		$status=$news_model->where(array('id'=>$id))->value('status');
		if($status==1){
			$statedata = array('status'=>0);
			$news_model->where(array('id'=>$id))->setField($statedata);
			$this->success('未审');
		}else{
			$statedata = array('status'=>1);
			$news_model->where(array('id'=>$id))->setField($statedata);
			$this->success('已审');
		}
	}
    /**
     * 回收站列表
     */
	public function goods_list_back()
	{
	$keytype = input('keytype','goods_title');
		$key     = input('key');
		$news_l  = input('news_l');
		$status  = input('status','');
		$cate    = input('cate',0);
		$diyflag=input('diyflag','');
		//查询：时间格式过滤 获取格式 2015-11-12 - 2015-11-18
		$sldate=input('reservation','');
		$arr = explode(" - ",$sldate);
        if(count($arr)==2){
            $arrdateone=strtotime($arr[0]);
            $arrdatetwo=strtotime($arr[1].' 23:55:55');
            $map['add_times'] = array(array('egt',$arrdateone),array('elt',$arrdatetwo),'AND');
        }
		//map架构查询条件数组
		$map['goods_back']= 1;
		if(!empty($key)){
			if($keytype=='goods_title'){
				$map[$keytype]= array('like',"%".$key."%");
			}else{
				$map[$keytype]= $key;
			}
		}
		if ($status!='')
			$map['a.status']= array('eq',$status);

		if (!empty($news_l))
			$map['goods_l']= array('eq',$news_l);

		if ($cate!=''){
			$ids = get_cate_byid('category',$cate,1,2);
			$map['cid']= array('in',implode(",", $ids));
		}
		
		$where = $diyflag ? " FIND_IN_SET('$diyflag',goods_flag) ":'';
		$good_model =new GoodsModel;
		$goods_list =$good_model->alias("a")->field('a.*,b.cid,c.cate_name')
				->join(config('database.prefix').'goods_cate b','a.id = b.gid')
				->join(config('database.prefix').'category c','b.cid =c.id')
				->where($map)->where($where)->order('add_times desc')->paginate(config('paginate.list_rows'),false,['query'=>get_query()]);
	 
		 
		
		$show = $goods_list->render();
		$show = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$show);
		$this->assign('page',$show);
		//商品属性数据
		$diyflag_list=Db::name('diyflag')->where('diyflag_model',$this->mode)->select();
		$this->assign('diyflag',$diyflag_list);
		//栏目数据
		
		
		$where=[];
		$where['model'] = array('eq',$this->mode);
		$where['cate_open']= array('eq',1);
		 
		$cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
		$menu_text = menu_left($cate_list_all,'id','parentid');
		$this->assign('menu',$menu_text);
 		
		$this->assign('status',$status);
		$this->assign('cate',$cate);
		$this->assign('keytype',$keytype);
		$this->assign('keyy',$key);
		$this->assign('news_l',$news_l);
		$this->assign('sldate',$sldate);
		$this->assign('diyflag_check',$diyflag);

		$this->assign('goods',$goods_list);
		if(request()->isAjax()){
			return $this->fetch('ajax_goods_back');
		}else{
			return $this->fetch();
		}	
	}
    /**
     * 还原商品
     */
	public function goods_list_back_open()
	{
		$p=input('p');
		$news_model=new GoodsModel;
		$rst=$news_model->where('id',input('n_id'))->setField('goods_back',0);//转入正常
		if($rst!==false){
			$this->success('商品还原成功',url('admin/Goods/goods_list_back',array('p' => $p)));
		}else{
			$this -> error("商品还原失败！",url('admin/Goods/goods_list_back',array('p' => $p)));
		}
	}
    /**
     * 彻底删除(单个)
     */
	public function goods_list_back_del()
	{
		$n_id= input('n_id');
		$p   = input('p');
		$news_model=new GoodsModel;
		if (empty($n_id)){
			$this->error('参数错误',url('admin/Goods/goods_back',array('p' => $p)));
		}else{
			$rst=$news_model->where('id',input('n_id'))->delete();
			if($rst!==false){
				$this->success('商品彻底删除成功',url('admin/Goods/goods_list_back',array('p' => $p)));
			}else{
				$this -> error("商品彻底删除失败！",url('admin/Goods/goods_list_back',array('p' => $p)));
			}
		}
	}
    /**
     * 彻底删除(全选)
     */
	public function goods_list_back_alldel()
	{
		$p = input('p');
		$ids = input('n_id/a');
		if(empty($ids)){
			$this -> error("请选择删除商品",url('admin/Goods/goods_list_back',array('p'=>$p)));//判断是否选择了商品ID
		}
		if(is_array($ids)){//判断获取商品ID的形式是否数组
			$where = 'id in('.implode(',',$ids).')';
		}else{
			$where = 'id='.$ids;
		}
		$news_model=new GoodsModel;
		$rst=$news_model->where($where)->delete();
		if($rst!==false){
			$this->success("成功把商品删除，不可还原！",url('admin/Goods/goods_list_back',array('p'=>$p)));
		}else{
			$this->error("商品彻底删除失败！",url('admin/Goods/goods_list_back',array('p' => $p)));
		}
	}
	
	
	//===================   商品分类部分程序  ==================================
	
	/* 商品分类列表  */
	public function cate_list(){
	    $cate_l=input('cate_l');
	    $where=array();
	    if(!empty($cate_l)){
	        $where['cate_l']=array('eq',$cate_l);
	    }
	    $where['model'] = array('eq',$this->mode);
	    
	    $pid   = input('pid',0);
	    $level = input('level',0);
	    $id_str= input('id','pid');	    
	    $cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
	    
	    
	    $where['parentid'] = array('eq',$pid);
	    $cate_list = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
	    
	     
	    $arr     = menu_left($cate_list,'id','parentid','─',$pid,$level,$level*20);
	    $arr_all = menu_left($cate_list_all,'id','parentid','─',0,$level,$level*20);
	    
	    $this->assign('cate_list',$arr);
	    $this->assign('cate_list_all',$arr_all);
	    $this->assign('pid',$id_str);
	    if(request()->isAjax()){
	        return $this->fetch('ajax_cate_list');
	    }else{
	        return $this->fetch();
	    } 
	}
	/* 保存商品分类  */
	public function cate_list_add(){
	    $pid  = input('parentid') ? input('parentid/d'):input('pid/d');
	    $options_model=new OptionsModel;
	    
	    
	    $tpls=$options_model->tpls($this->lang); 
	    $this->assign('tpls',$tpls);
	    
	    $where=array();
	    $where['model'] = array('eq',$this->mode);
	    $where['cate_open']= array('eq',1);
	    $cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
	    $menu_text = menu_left($cate_list_all,'id','parentid');
	    $this->assign('menu',$menu_text);  
	    $this->assign('parentid',$pid);
	    return $this->fetch();
	}
	
	
	/* 保存商品分类  */
	public function cate_list_runadd(){
	    if (!request()->isAjax()){
	        $this->error('提交方式不正确',url('admin/Goods/cate_list'));
	    }else{
	        //处理图片
	        $img_url='';
	        $file = request()->file('file0');
	        if($file){
	            if(config('storage.storage_open')){
	                //七牛
	                $upload = \Qiniu::instance();
	                $info = $upload->upload();
	                $error = $upload->getError();
	                if ($info) {
	                    $img_url= config('storage.domain').$info[0]['key'];
	                }else{
	                    $this->error($error,url('admin/Goods/cate_list'));
	                }
	            }else{
	                $validate=config('upload_validate');
	                $info = $file->validate($validate)->rule('uniqid')->move(ROOT_PATH . config('upload_path') . DS . date('Y-m-d'));
	                if($info) {
	                    $img_url=config('upload_path'). '/' . date('Y-m-d') . '/' . $info->getFilename();
	                    //写入数据库
	                    $data['uptime']=time();
	                    $data['filesize']=$info->getSize();
	                    $data['path']=$img_url;
	                    Db::name('plug_files')->insert($data);
	                }else{
	                    $this->error($file->getError(),url('admin/Goods/cate_list'));
	                }
	            }
	        }
	        //构建数组
	        $data=array(
	            'cate_name'=>input('cate_name'),
	            'cate_l'=>input('cate_l','zh-cn'),
	            'cate_type'=>input('cate_type'),
	            'parentid'=>input('parentid'),
	            'cate_listtpl'=>input('cate_listtpl'),
	            'cate_newstpl'=>input('cate_newstpl'),
	            'cate_open'=>input('cate_open',0),
	            'listorder'=>input('listorder'),
	            'cate_seo_title'=>input('cate_seo_title'),
	            'cate_seo_key'=>input('cate_seo_key'),
	            'cate_seo_des'=>input('cate_seo_des'),
	            'cate_content'=>htmlspecialchars_decode(input('cate_content')),
	            'cate_img'=>$img_url,
	        );
	        $rst = CategoryModel::create($data);
	        if($rst!==false){
	            cache('site_cate_main',null);
	            $this->success('分类添加成功',url('admin/Goods/cate_list'));
	        }else{
	            $this->error('分类添加失败',url('admin/Goods/cate_list'));
	        }
	    }
	}
	
	/* 编辑商品分类 */
	public function cate_list_edit(){
	    $options_model=new OptionsModel;
	    $tpls=$options_model->tpls($this->lang);
	    $this->assign('tpls',$tpls);
	    
	    $id   = input('n_id/d',0);
	    if($id == 0)
	        $this->error('分类信息获取失败！',url('admin/Goods/cate_list'));
	    
	    $info = Db::name("category")->find($id);
	    
	    $where=array();
	    $where['model'] = array('eq',$this->mode);
	    $where['cate_open']= array('eq',1);
	    $cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
	    $menu_text = menu_left($cate_list_all,'id','parentid');
	    $this->assign('menu',$menu_text);
	    $this->assign('info',$info);
	    return $this->fetch();
	}
	
	
	
	/* 保存编辑商品分类  */
	public function cate_list_runedit(){
	    if (!request()->isAjax()){
	        $this->error('提交方式不正确',url('admin/Goods/cate_list'));
	    }else{
	        $checkpic=input('checkpic');
	        $oldcheckpic=input('oldcheckpic');
	        $img_url='';
	        if ($checkpic!=$oldcheckpic){
	            $file = request()->file('file0');
	            if($file){
	                if(config('storage.storage_open')){
	                    //七牛
	                    $upload = \Qiniu::instance();
	                    $info = $upload->upload();
	                    $error = $upload->getError();
	                    if ($info) {
	                        $img_url= config('storage.domain').$info[0]['key'];
	                    }else{
	                        $this->error($error,url('admin/Goods/cate_list'));//否则就是上传错误，显示错误原因
	                    }
	                }else{
	                    $validate=config('upload_validate');
	                    $info = $file->validate($validate)->rule('uniqid')->move(ROOT_PATH . config('upload_path') . DS . date('Y-m-d'));
	                    if($info) {
	                        $img_url=config('upload_path'). '/' . date('Y-m-d') . '/' . $info->getFilename();
	                        //写入数据库
	                        $data['uptime']=time();
	                        $data['filesize']=$info->getSize();
	                        $data['path']=$img_url;
	                        Db::name('plug_files')->insert($data);
	                    }else{
	                        $this->error($file->getError(),url('admin/Goods/cate_list'));
	                    }
	                }
	            }
	        }
	       //构建数组
	        $data=array(
	            'id'       =>input('id/d'),
	            'cate_name'=>input('cate_name'),
	            'cate_l'=>input('cate_l','zh-cn'),
	            'cate_type'=>input('cate_type'),
	            'parentid'=>input('parentid'),
	            'cate_listtpl'=>input('cate_listtpl'),
	            'cate_newstpl'=>input('cate_newstpl'),
	            'cate_open'=>input('cate_open',0),
	            'listorder'=>input('listorder'),
	            'cate_seo_title'=>input('cate_seo_title'),
	            'cate_seo_key'=>input('cate_seo_key'),
	            'cate_seo_des'=>input('cate_seo_des'),
	            'cate_content'=>htmlspecialchars_decode(input('cate_content')),
	        );
	        if ($checkpic!=$oldcheckpic){
	            $data['cate_img']=$img_url;
	        }
	        $rst = CategoryModel::update($data);
	        if($rst!==false){
	            cache('site_nav_main',null);
	            $this->success('商品分类修改成功',url('admin/Goods/cate_list'));
	        }else{
	            $this->error('商品分类修改失败',url('admin/Goods/cate_list'));
	        }
	    }
	    
	    
	    
	    
	    
	}
	/* 商品分类排序  */
	public function cate_list_order(){
	    if (!request()->isAjax()){
	        $this->error('提交方式不正确',url('admin/Goods/cate_list'));
	    }else{
	        $list=[];
	        foreach (input('post.') as $n_id => $news_order){
	            $list[]=['id'=>$n_id,'listorder'=>$news_order];
	        }
	        $cateModel = new CategoryModel;
	        $cateModel->saveAll($list);
	       
	        $this->success('排序更新成功',url('admin/Goods/cate_list'));
	    } 
	}
	
	
	/* 商品分类状态  */
	public function cate_list_state(){
	    $id = input('x');
	    $status = Db::name('category')->where(array('id'=>$id))->value('cate_open');
	    if($status==1){
	        Db::name('category')->where(array('id'=>$id))->setField('cate_open',0);
	        $this->success('未审');
	    }else{
	        Db::name('category')->where(array('id'=>$id))->setField('cate_open',1);
	        $this->success('已审');
	    }  
	}
	
	
	
	/* 删除商品分类  */
	public function cate_list_del(){
	    $p   = input('p');
	    $ids = input('n_id/a');
	    if(empty($ids)){
	        $this -> error("请选择删除商品分类",url('admin/Goods/cate_list',array('p'=>$p)));//判断是否选择了商品ID
	    }
	    
	    if(is_array($ids)){//判断获取商品ID的形式是否数组
	        $where = 'id in ('.implode(',',$ids).') ';
	    }else{
	        $where = 'id = '.$ids;
	    }
	    
	    $jcount = Db::name('goods_cate')->where(str_replace("id",'cid',$where))->count();
	    if($jcount >0)
	        $this -> error("该分类下存在商品，不能删除！",url('admin/Goods/cate_list',array('p'=>$p)));//判断是否选择了商品ID
	     
	    $rst = Db::name('category')->where($where." and model ='".$this->mode."' ")->delete();
	    if($rst!==false){
	        $this->success("成功删除商品分类！",url('admin/Goods/goods_back',array('p'=>$p)));
	    }else{
	        $this -> error("商品分类删除失败！",url('admin/Goods/goods_back',array('p' => $p)));
	    }
	}
	//===================   商品分类部分程序结束   ===============================
	
	
	
	//===================   订单管理部分程序  ==================================
	public function order_list(){
	    $state_pay   = input('state_pay/d',0); //付款状态
	    $state_trade = input('state_trade/d',0); //交易状态
	    $key         = input('key');
	    $cate        = input('cate',0);
	    
	    $map         = [];
	    //查询：时间格式过滤 获取格式 2015-11-12 - 2015-11-18
	    $sldate=input('reservation','');
	    $arr = explode(" - ",$sldate);
	    if(count($arr)==2){
	        $arrdateone=strtotime($arr[0]);
	        $arrdatetwo=strtotime($arr[1].' 23:55:55');
	        $map['add_times'] = array(array('egt',$arrdateone),array('elt',$arrdatetwo),'AND');
	    }
	    //map架构查询条件数组
	    
	    if(!empty($key))
	       $map['goods_title']= array('like',"%".$key."%");
	         
	    if ($state_pay != 0)
	        $map['state_pay']= array('eq',$state_pay);
	    
	    if ($state_trade != 0)
	        $map['state_trade']= array('eq',$state_trade);
	    
	    if ($cate!=''){
	        $ids = get_cate_byid('category',$cate,1,2);
	        $map['cid']= array('in',implode(",", $ids));
	    }
	    
// 	    $where = $diyflag ? " FIND_IN_SET('$diyflag',goods_flag) ":'';
	    $where = '';
	    $good_model =new GoodsOrderModel;
	    $goods_list =$good_model->alias("a")->field('a.*,b.goods_title,b.goods_flag,c.cid,d.cate_name,e.address,e.man,e.mobile,e.zipcode,f.name as province,g.name as city,h.name as district ')
	    ->join(config('database.prefix').'goods b','a.gid = b.id','left')
	    ->join(config('database.prefix').'goods_cate c','b.id =c.gid','left')
	    ->join(config('database.prefix').'category d','c.cid =d.id','left')
	    ->join(config('database.prefix').'member_address e ','a.address_id = e.id','left')
	    ->join(config('database.prefix').'region f ','e.province = f.id','left')
	    ->join(config('database.prefix').'region g ','e.city = g.id','left')
	    ->join(config('database.prefix').'region h ','e.district = h.id','left')
	    ->where($map)->where($where)->order('add_time desc')->paginate(config('paginate.list_rows'),false,['query'=>get_query()]);
	    
	    //dump($goods_list);exit;
	    $show = $goods_list->render();
		$show = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$show);
		$this->assign('page',$show);
	    
	    $where=array();
	    $where['model'] = array('eq',$this->mode);
	    $where['cate_open']= array('eq',1);
	    $cate_list_all = Db::name("category")->where($where)->order('cate_l Desc,listorder')->select();
	    $menu_text = menu_left($cate_list_all,'id','parentid');
	    $this->assign('menu',$menu_text);
	    
	    foreach($goods_list as $k=>$v){
	        $goods_list[$k]['state_pay_name'] = isset($this->state_pay_list[$v['state_pay']]) ? $this->state_pay_list[$v['state_pay']]:'付款状态';
	        $goods_list[$k]['state_trade_name'] = isset($this->state_trade_list[$v['state_trade']]) ? $this->state_trade_list[$v['state_trade']]:'交易状态';
	    
	        $goods_list[$k]['my_address'] = $v['province'].$v['city'].$v['district'].$v['address'].
	                                        (empty($v['man'])?'':"（{$v['man']}）").
	                                        (empty($v['mobile'])?'':"（电话 {$v['mobile']}）");
	    }
	    

	    $this->assign([
	        'cate'=>$cate,
	        'state_pay'=>$state_pay,
	        'state_trade'=>$state_trade,
	        'state_pay_list'=>$this->state_pay_list,
	        'state_trade_list'=>$this->state_trade_list,
	        'sldate'=>$sldate,
	        'keyy'=>$key,
	        'goods'=>$goods_list,
	    ]);
	    
	    if(request()->isAjax()){
	        return $this->fetch('ajax_order_list');
	    }else{
	        return $this->fetch();
	    } 
	    
	}
	
	//订单详情
	public function order_list_edit(){
	  $id = input('id/d');   
	  $orderModel =new GoodsOrderModel;
	  $info       = $orderModel->getInfo($id);
	  if($info){
	     $info     = $info->toArray();
	     $province = Db::name('Region')->where ( array('pid'=>1) )->select ();
	     
	     $province_id  = isset($info['address_cache']['province']) ? $info['address_cache']['province']:1;
	     $city_id      = isset($info['address_cache']['city']) ? $info['address_cache']['city']:0;
	     $district_id  = isset($info['address_cache']['district']) ? $info['address_cache']['district']:0;
	     
	      
	     $city     = Db::name('Region')->where ( array('pid'=>$province_id) )->select ();
	     $district = Db::name('Region')->where ( array('pid'=>$city_id) )->select ();
	     
	     
	     $this->assign([
	         'info' =>$info,
	         'state_pay_list'  =>$this->state_pay_list,
	         'state_trade_list'=>$this->state_trade_list,
	         'province'        =>$province,
	         'city'            =>$city,
	         'district'        =>$district,
	     ]);   
	     return $this->fetch('order_list_edit');
	  }else{
	     $this->error('不存在该订单记录！'); 
	  }
	   
	}
	
	public function order_list_runedit(){
	    if (!request()->isAjax()){
	        $this->error('提交方式不正确',url('admin/Goods/order_list'));
	    }else{
	        $data = input('post.');
	        $info = Db::name("goods_order")->where("id",$data['id'])->find();
	        $info['address_cache'] = unserialize($info['address_cache']);
	        $info = array_merge($info,$data['order']);
	        $info['address_cache'] = array_merge($info['address_cache'],$data['address_cache']);
	        $info['last_time']   = time();
	        $info['address_cache'] = serialize($info['address_cache']);
	         
	        $res = Db::name("goods_order")->where("id",$data['id'])->update($info);
	        if($res !== false){
	             $this->success('订单修改成功,返回列表页',url('admin/Goods/order_list'));
	        }else{
	             $this->error('订单修改失败',url('admin/Goods/order_list'));
	        }
        
	    }    
	}
	
	
	//订单状态
	public function order_list_state(){
	    $id  = input('id/d');
	    $val = input('va/d');
	    $field = input('field','','strip_tags');
	    $orderModel = new GoodsOrderModel;
	    $p   = input('p/d');
	    $rst = $orderModel->where('id',$id)->setField($field,$val);//转入正常
	    if($rst!==false){
	        $this->success('状态修改成功',url('admin/Goods/order_list',array('p' => $p)));
	    }else{
	        $this -> error("状态修改失败！",url('admin/Goods/order_list',array('p' => $p)));
	    }
	 
	}
	
	public function order_list_del()
	{
	    $n_id= input('id');
	    $p   = input('p');
	    $orderModel = new GoodsOrderModel;
	    if (empty($n_id)){
	        $this->error('参数错误',url('admin/Goods/order_list',array('p' => $p)));
	    }else{
	        $rst = $orderModel->where('id',$n_id)->delete();
	        if($rst!==false){
	            $this->success('订单删除成功',url('admin/Goods/order_list',array('p' => $p)));
	        }else{
	            $this -> error("订单删除失败！",url('admin/Goods/order_list',array('p' => $p)));
	        }
	    }
	}
	
	/**
	 * 彻底删除(全选)
	 */
	public function order_list_alldel()
	{
	    $p = input('p');
	    $ids = input('n_id/a');
	    if(empty($ids)){
	        $this -> error("请选择删除订单",url('admin/Goods/order_list',array('p'=>$p)));//判断是否选择了商品ID
	    }
	    if(is_array($ids)){//判断获取商品ID的形式是否数组
	        $where = 'id in('.implode(',',$ids).')';
	    }else{
	        $where = 'id='.$ids;
	    }
	    $orderModel = new GoodsOrderModel;
	    $rst=$orderModel->where($where)->delete();
	    if($rst!==false){
	        $this->success("成功删除订单！",url('admin/Goods/order_list',array('p'=>$p)));
	    }else{
	        $this->error("订单删除失败！",url('admin/Goods/order_list',array('p' => $p)));
	    }
	}
	
}